package defense

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"wrblog-api-go/app/common/constants"
	"wrblog-api-go/app/common/token"
	"wrblog-api-go/pkg/client"
	"wrblog-api-go/pkg/redis"
	"wrblog-api-go/pkg/result"
	"wrblog-api-go/pkg/status"
	"wrblog-api-go/pkg/utils"
)

func UploadIpLock(num int) gin.HandlerFunc {
	return func(c *gin.Context) {
		row, _ := c.Get("loginUser")
		loginUser := row.(token.LoginUser)
		clientInfo := client.GetClient(c)
		sum := 0
		v := redis.Get(fmt.Sprintf("%s%s", constants.UPLOAD_IP_LOCK, clientInfo.IpAddr))
		if !utils.IsEmpty(v) {
			sum, _ = strconv.Atoi(v)
			if num < sum {
				result.Wrap(status.TooManyRequests, fmt.Sprintf("别上传了，12小时内只能上传%d个文件！", sum)).Json(c)
				c.Abort()
				return
			}
		}
		sum++
		redis.SetTime(fmt.Sprintf("%s%d:%s", constants.UPLOAD_IP_LOCK, loginUser.UserId, clientInfo.IpAddr), strconv.Itoa(sum), 12*time.Hour)
		c.Next()
	}
}

func IpLock(num int) gin.HandlerFunc {
	return func(c *gin.Context) {
		clientInfo := client.GetClient(c)
		sum := 0
		v := redis.Get(fmt.Sprintf("%s%s", constants.IP_LOCK, clientInfo.IpAddr))
		if !utils.IsEmpty(v) {
			sum, _ = strconv.Atoi(v)
			if num < sum {
				result.Wrap(status.TooManyRequests, fmt.Sprintf("别攻击了，你一个小时内调了%d次接口！", sum)).Json(c)
				c.Abort()
				return
			}
		}
		sum++
		redis.SetTime(fmt.Sprintf("%s%s", constants.IP_LOCK, clientInfo.IpAddr), strconv.Itoa(sum), 1*time.Hour)
		c.Next()
	}
}
